import 'package:flutter/material.dart';
import 'package:flutter_app/commom/Global.dart';

import 'package:flutter_app/models/ganttChart.dart';
import 'dart:math';


class GanttChartScreen extends StatefulWidget {

  GanttChartScreen({
    Key key,
    @required this.projects,
    @required this.users,
    @required this.toDate,
    @required this.fromDate,
    this.title
  }) : super(key: key);
  final List<Project> projects;
  final List<User> users;
  final String title;
  final DateTime fromDate;
  final DateTime toDate;
  @override
  State<StatefulWidget> createState() {
    return new GanttChartScreenState(projects, users, title, fromDate, toDate);
  }
}

class GanttChartScreenState extends State<GanttChartScreen> with TickerProviderStateMixin {
  final List<Project> projects;
  final List<User> users;
  final String title;
  final DateTime fromDate;
  final DateTime toDate;
  GanttChartScreenState(this.projects, this.users, this.title, this.fromDate, this.toDate);
  AnimationController animationController;
//此处可以比较开始日期与当前日期，
// 若当前日期早于开始日期，则使用开始日期，若当前日期晚于开始日期，则使用当前时间
  List<User> usersInChart;
  List<Project> projectsInChart;

  @override
  void initState() {
    super.initState();
    //使用
    animationController = new AnimationController(
        duration: Duration(microseconds: 2000), vsync: this);
    animationController.forward();

    //users.forEach((element) {print(element.name);});
    projectsInChart = projects;
    usersInChart = users;
  }

  Widget buildAppBar() {
    return AppBar(
      title: Text(title),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(new FocusNode());
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
              child: GanttChart(
                animationController: animationController,
                fromDate: fromDate,
                toDate: toDate,
                projects: projects,
                users: users,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class GanttChart extends StatelessWidget {
  final AnimationController animationController;
  final DateTime fromDate;
  final DateTime toDate;
  final String title;
  final List<Project> projects;
  final List<User> users;

  int viewRange;
  int viewRangeToFitScreen = 6;
  Animation<double> width;

  GanttChart({
    this.animationController,
    this.fromDate,
    this.toDate,
    this.projects,
    this.users,
    this.title
  }) {
    viewRange = calculateNumberOfDaysBetween(fromDate, toDate) + 1;
  }

  int calculateNumberOfDaysBetween(DateTime from, DateTime to) {
    return to.difference(from).inDays;
  }
  //计算每道工序到左侧的距离
  int calculateDistanceToLeftBorder(DateTime projectStartedAt) {
    if (projectStartedAt.compareTo(fromDate) <= 0) {
      return 0;
    } else
      //print(calculateNumberOfDaysBetween(fromDate, projectStartedAt));
      return calculateNumberOfDaysBetween(fromDate, projectStartedAt);
  }
  //计算每道工序的长度
  int calculateRemainingWidth(
      DateTime projectStartedAt, DateTime projectEndedAt) {
    int projectLength =
    calculateNumberOfDaysBetween(projectStartedAt, projectEndedAt);
    //print(projectLength);
    //if(projectLength == 0) projectLength = projectLength + 1;
    if (projectStartedAt.compareTo(fromDate) >= 0 &&
        projectStartedAt.compareTo(toDate) <= 0) {
      //viewRange：gantt图的总长度
      if (projectLength <= viewRange)
        return projectLength;
      else
        return viewRange -
            calculateNumberOfDaysBetween(fromDate, projectStartedAt);
    } else if (projectStartedAt.isBefore(fromDate) &&
        projectEndedAt.isBefore(fromDate)) {
      return 0;
    } else if (projectStartedAt.isBefore(fromDate) &&
        projectEndedAt.isBefore(toDate)) {
      return projectLength -
          calculateNumberOfDaysBetween(projectStartedAt, fromDate);
    } else if (projectStartedAt.isBefore(fromDate) &&
        projectEndedAt.isAfter(toDate)) {
      return viewRange;
    }
    return 0;
  }

  List<Widget> buildChartBars(
      List<Project> data, double chartViewWidth) {
    List<Widget> chartBars = new List();

    for(int i = 0; i < data.length; i++) {
      var remainingWidth =
      calculateRemainingWidth(data[i].startTime, data[i].endTime) +1;
      //print(remainingWidth);
      if (remainingWidth > 0) {
        chartBars.add(Container(
          decoration: BoxDecoration(
              color: Colors.black12,
              borderRadius: BorderRadius.circular(10.0)),
          height: 25.0,
          width: remainingWidth * chartViewWidth / viewRangeToFitScreen,
          //margin:外边距
          margin: EdgeInsets.only(
              left: calculateDistanceToLeftBorder(data[i].startTime) *
                  chartViewWidth /
                  viewRangeToFitScreen,
              top: i == 0 ? 4.0 : 2.0,
              bottom: i == data.length - 1 ? 4.0 : 2.0
          ),
          alignment: Alignment.centerLeft,
          child: Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: Text(
              data[i].name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 10.0),
            ),
          ),
        ));
      }
    }
    return chartBars;
  }

  Widget buildHeader(double chartViewWidth) {
    List<Widget> headerItems = new List();

    DateTime tempDate = fromDate;

    headerItems.add(Container(
      width: chartViewWidth / viewRangeToFitScreen,
      child: new Text(
        '承包人',
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 10.0,
        ),
      ),
    ));
    //viewRange：起始日期至截止日期
    for (int i = 0; i < viewRange; i++) {
      headerItems.add(Container(
        width: chartViewWidth / viewRangeToFitScreen,
        child: new Text(
          tempDate.year.toString() + '/' +tempDate.month.toString() + '/' + tempDate.day.toString(),
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 10.0,
          ),
        ),
      ));
      tempDate = tempDate.add(new Duration(days: 1));
    }

    return Container(
      height: 25.0,
      color: Colors.grey.withAlpha(200),
      child: Row(
        children: headerItems,
      ),
    );
  }

  Widget buildGrid(double chartViewWidth) {
    List<Widget> gridColumns = new List();

    for (int i = 0; i <= viewRange; i++) {
      gridColumns.add(Container(
        decoration: BoxDecoration(
            border: Border(
                right:
                BorderSide(color: Colors.white.withAlpha(200), width: 1.0))),
        width: chartViewWidth / viewRangeToFitScreen,
        //height: 300.0,
      ));
    }

    return Row(
      children: gridColumns,
    );
  }

  Widget buildChartForEachUser(
      List<Project> userData, double chartViewWidth, User user) {
    //Color color = randomColorGenerator();
    var chartBars = buildChartBars(userData, chartViewWidth);
    return Container(
      height: chartBars.length * 29.0 + 25.0 + 4.0,
      child: ListView(
        physics: new ClampingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          Stack(fit: StackFit.loose, children: <Widget>[
            buildGrid(chartViewWidth),
            buildHeader(chartViewWidth),
            Container(
                margin: EdgeInsets.only(top: 25.0),
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Row(
                          children: <Widget>[
                            Container(
                                width: chartViewWidth / viewRangeToFitScreen,
                                height: chartBars.length * 29.0 + 4.0,
                                color: Colors.white.withAlpha(100),
                                child: Center(
                                  child: new RotatedBox(
                                    quarterTurns: chartBars.length * 29.0 + 4.0 > 50 ? 0 : 0,
                                    child: new Text(
                                      user.name,
                                      textAlign: TextAlign.center,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                )),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: chartBars,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                )),
          ]),
        ],
      ),
    );
  }

  List<Widget> buildChartContent(double chartViewWidth) {
    List<Widget> chartContent = new List();

    users.forEach((user) {

      //统计每名用户的工序
      List<Project> projectsOfUser = new List();

      projectsOfUser = projects.where((project) => project.participants.indexOf(user.id) != -1).toList();

      if (projectsOfUser.length > 0) {
        chartContent.add(buildChartForEachUser(projectsOfUser, chartViewWidth, user));
      }
    });

    return chartContent;
  }

  @override
  Widget build(BuildContext context) {
    var chartViewWidth = MediaQuery.of(context).size.width;
    var screenOrientation = MediaQuery.of(context).orientation;
    //更改方向
    screenOrientation == Orientation.landscape
        ? viewRangeToFitScreen = 12
        : viewRangeToFitScreen = 6;

    return Container(
      //删除内边距
        child: MediaQuery.removePadding(
          child: ListView(
              children: buildChartContent(chartViewWidth)
          ),
          removeTop: true,
          context: context,
        )
    );
  }
}

